<!DOCTYPE html>
<html lang="zh-CN">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.ico">
  <link rel="icon" type="image/png" href="/img/favorite.ico">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="小九的日常笔记">
  <meta name="author" content="小九">
  <meta name="keywords" content="笔记，博客，前端，html，css，javascript，面试题，前端面试题">
  <title>神奇的grid布局 - 小九的书柜</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/github-gist.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->

  
<link rel="stylesheet" href="/css/my.css">



<!-- 
<link rel="stylesheet" href="/css/message.css">
 -->
<!-- 
<link rel="stylesheet" href="https://at.alicdn.com/t/font_1117508_wxidm5ry7od.css">
 -->

  <script  src="/js/utils.js" ></script>
<meta name="generator" content="Hexo 4.2.1"></head>



<body>
  
  <div id="background">
    <!--  -->
    <header style="height: 70vh;">
      <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
      href="/">&nbsp;<strong>jLongYan's blog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
      data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
      aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/">
            <i class="iconfont icon-home-fill"></i>
            首页
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/archives/">
            <i class="iconfont icon-archive-fill"></i>
            归档
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/categories/">
            <i class="iconfont icon-category-fill"></i>
            分类
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/tags/">
            <i class="iconfont icon-tags-fill"></i>
            标签
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/links/">
            <i class="iconfont icon-link-fill"></i>
            友链
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/about/">
            <i class="iconfont icon-user-fill"></i>
            关于
          </a>
        </li>
        
        
        
        <li class="nav-item" onclick="switchDarkMode()">
          <span id="dark"></span>
        </li>
        
      </ul>
    </div>
  </div>
</nav>
<style>
  .active {
    /* border-bottom: 1px solid #00FFFF; */
    color: #00FFFF !important;
  }
</style>

<script>
  var isNight = new Date().getHours() >= 22 || new Date().getHours() < 5; // 指定时间
  // 依次判断 系统暗黑模式 指定时间 缓存 dark
  if (matchMedia('(prefers-color-scheme: dark)').matches || isNight || localStorage.getItem('dark') === '1') {
    if (!(isNight && localStorage.getItem('noDark') === '1')) {
      document.body.classList.add('dark');
    }
  }
  //点击事件
  function switchDarkMode() {
    if ($('body').hasClass('dark')) {
      // checkWallaper()
      document.getElementById('dark').style.backgroundImage = 'url(/img/太阳.png)'
      document.body.classList.remove('dark');
      localStorage.setItem('noDark', '1');
      localStorage.setItem('dark', '0');
    } else {
      document.getElementById('dark').style.backgroundImage = 'url(/img/月亮.png)'
      document.body.classList.add('dark');
      localStorage.setItem('dark', '1');
      localStorage.setItem('noDark', '0');
      // checkWallaper()
    }
  }

</script>



      <!-- 如果需要采用配置文件的路径 在下面的div粘贴此段代码进去即可 目前采用的是 自定义的随机图片 -->
      <!-- style="background: url('/headImg/headImg.jpg') no-repeat center center;background-size: cover;" -->
      <div class="view intro-2" id="indexBackground" parallax=true
        style='background-size:cover'>
        <div class="full-bg-img">
          <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.1)">
            <div class="container text-center white-text fadeInUp">

              <span class="h2" id="subtitle">
                
              </span>

              <div id="yiyan" onclick="watchYiyan()">只有极其努力，才能看起来毫不费力。</div>

              


              
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2018-07-10 18:36">
      2018年7月10日 晚上
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      3.6k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      43
       分钟
    </span>
  

  
  
    
  
</div>
<!-- <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script> -->
              
            </div>

            
            <div class="scroll-down-bar">
              <i class="iconfont icon-arrowdown"></i>
            </div>
            
          </div>
        </div>
      </div>
    </header>
    <!--  -->



    <main>
      
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
              <p class="note note-info">
                
                  本文最后更新于：2020年8月4日 晚上
                
              </p>
            
            <article class="markdown-body">
              <h4 id="神奇的Grid布局"><a href="#神奇的Grid布局" class="headerlink" title="神奇的Grid布局"></a>神奇的Grid布局</h4><hr>
<blockquote>
<p>本来以为，漂泊，就是家乡只有冬夏，再无春秋。现在才发现，漂泊，是连冬夏都没有了。</p>
</blockquote>
<h5 id="什么是flex"><a href="#什么是flex" class="headerlink" title="什么是flex"></a>什么是flex</h5><p>​        遥想当年，一手flex布局走天下，每每面试官问到关于关于布局方面的问题，大多离不开flex，当下看来flex布局确实是日常开发中最为常见的布局了，</p>
<blockquote>
<p>2009年,W3C提出了一种新的方案–<em>Flex布局</em>,可以简便、完整、响应式地实现各种页面布局。目前已得到所有现在浏览器的支持。</p>
</blockquote>
<p>​         距今来看已经十多年了，确确实实占据了前端布局中很大的地位，相比大家对flex都很熟悉，所以今天我们的主角就是——-&gt;  <code>Grid</code></p>
<h5 id="什么是Grid布局"><a href="#什么是Grid布局" class="headerlink" title="什么是Grid布局"></a>什么是Grid布局</h5><p>​        Grid布局又称网格布局，Grid 布局是网站设计的基础，CSS Grid 是创建网格布局最强大和最简单的工具。轻松使用 Grid 布局提高开发效率，对复杂的网页结构布局更加灵活。Grid 将网页划分成一个个网格，可以任意组合不同的网格，做出各种各样的布局。网格是一组相交的水平线和垂直线，它定义了网格的列和行。我们可以将网格元素放置在与这些行和列相关的位置上。我们比较熟悉的比如说坐标轴，坐标点；如果你看到下面这样一个网格首先想到是这不就是被淘汰的表格吗，表格之所以被淘汰最主要在性能方面，然而我们不得不承认表格对于整个网页的布局来说有一定的便利性。那么现在的网格布局就可以把表格里面的一些较好的方便的东西抽出来，然后把性能方面较差的地方去掉，所以说网格布局会成为将来互联网企业的一个热潮是有原因的。我们可以把一个网页理解成一个网格，然后往里面填充东西即可.</p>
<p><img src="/articleImg/grid1.jpg" srcset="/img/loading.gif" alt="grid1"></p>
<p>当我们吧网页划分成这样的一个一个格子的时候，是否就觉得很清晰了呢，当然这样还不够，我们在有的时候也需要像tabel那样对单元格进行合并或者删除，例如下面这样：</p>
<p><img src="/articleImg/grid2.jpg" srcset="/img/loading.gif" alt="grid2"></p>
<p>​        总之你可以对这些格子随意操作，不再再仅限于一条轴线，这里有很多条了。让我们上代码看看这些在浏览器中如何实现吧</p>
<h5 id="demo-lt-基础运用-gt"><a href="#demo-lt-基础运用-gt" class="headerlink" title="demo&lt;基础运用&gt;"></a>demo&lt;基础运用&gt;</h5><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"wrapper"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box box1"</span>&gt;</span>box 1<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box box2"</span>&gt;</span>box 2<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box box3"</span>&gt;</span>box 3<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box box4"</span>&gt;</span>box 4<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box box5"</span>&gt;</span>box 5<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">style</span>&gt;</span>
<span class="css">    <span class="hljs-selector-class">.wrapper</span>&#123;</span>
        padding: 1rem;
    &#125;
<span class="css">    <span class="hljs-selector-class">.wrapper</span>&gt;<span class="hljs-selector-tag">div</span>&#123;</span>
<span class="css">        <span class="hljs-selector-tag">background</span>: <span class="hljs-selector-id">#ccc</span>;</span>
        padding: 1rem;
    &#125;
<span class="css">    <span class="hljs-selector-class">.wrapper</span>&gt;<span class="hljs-selector-tag">div</span><span class="hljs-selector-pseudo">:nth-child(odd)</span>&#123;</span>
<span class="css">        <span class="hljs-selector-tag">background</span>: <span class="hljs-selector-id">#ddd</span>;</span>
    &#125;
 <span class="hljs-tag">&lt;/<span class="hljs-name">style</span>&gt;</span></code></pre>

<p>先上五个盒子，看看本来的样子吧：</p>
<p><img src="/articleImg/grid3.jpg" srcset="/img/loading.gif" alt="grid3"></p>
<p>对于不使用任何布局的时候就是这样子啦:五个div独占一行，这个时候让我们改造一下让他变成像上面一样的格子吧，我们来做一个一行有三个格子的网格出来吧 </p>
<pre><code class="hljs css">&lt;<span class="hljs-selector-tag">style</span>&gt;
    <span class="hljs-selector-class">.wrapper</span>&#123;
        <span class="hljs-attribute">display</span>: grid;
        <span class="hljs-attribute">padding</span>: <span class="hljs-number">1rem</span>;
        <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(<span class="hljs-number">3</span>,<span class="hljs-number">1</span>fr);
        <span class="hljs-attribute">grid-gap</span>: <span class="hljs-number">1rem</span>;
        <span class="hljs-attribute">grid-auto-rows</span>:<span class="hljs-built_in">minmax</span>(<span class="hljs-number">100px</span>,auto);
        &#125;
    <span class="hljs-selector-class">.wrapper</span>&gt;<span class="hljs-selector-tag">div</span>&#123;
        <span class="hljs-attribute">background</span>: <span class="hljs-number">#ccc</span>;
        <span class="hljs-attribute">padding</span>: <span class="hljs-number">1rem</span>;
    &#125;
    <span class="hljs-selector-class">.wrapper</span>&gt;<span class="hljs-selector-tag">div</span><span class="hljs-selector-pseudo">:nth-child(odd)</span>&#123;
        <span class="hljs-attribute">background</span>: <span class="hljs-number">#ddd</span>;
    &#125;
 &lt;/style&gt;</code></pre>

<p><img src="/articleImg/grid4.jpg" srcset="/img/loading.gif" alt="grid4"></p>
<p>可以看到只需添加两行代码，轻松实现，<code>display: grid;</code>和flex布局同理申明一个容器，表示外层的这个div为网格容器了，那么这一行呢<code>grid-template-columns: repeat(3,1fr);</code>这一行表示一行放三个盒子并且宽度一样，这里用到了一个repeat函数正常写法是这样，<code>grid-template-columns: 1fr 1fr 1fr;</code> 这样就代表一行三个格子，当然你可以写四个五个六七个，这里的fr就是一个单位（<code>弹性尺寸使用fr尺寸单位，其来自 “fraction” 或 “fractional unit” 单词的前两个字母，表示整体空间的一部分。</code>）fr是一个相对尺寸单位，表示剩余空间做等分，此项分配到的百分比(如果只有一个项使用此单位，那就占剩余空间的100%，所以多个项联合使用更有意义，在flex布局中也有用到，这里你可以自由搭配，当然这里也可以使用百分比例如：</p>
<pre><code class="hljs css">`<span class="hljs-selector-tag">grid-template-columns</span>: 30% 30% 40%;`</code></pre>

<p>当然了多种多样都可以，任你自由搭配，那么剩下两行呢：</p>
<blockquote>
<p><code>grid-gap: 1rem;</code>横纵轴的间距可以写两个参数，就是格子间的间距，可以自我尝试</p>
<p><code>grid-auto-rows:minmax(100px,auto);</code>这里用到了minmax函数表示最小高度为100px，如果文字撑起高度大于100px了，那么则自适应，这里只是为了大家看得更清晰添加的，可以自我尝试</p>
</blockquote>
<p>以上就是基础的grid布局两行代码上手，soeasy！！！ </p>
<p>接下来我们试试合并单元格吧，像图二一样合并各种格子自由搭配</p>
<h5 id="demo-lt-合并格子-gt"><a href="#demo-lt-合并格子-gt" class="headerlink" title="demo&lt;合并格子&gt;"></a>demo&lt;合并格子&gt;</h5><pre><code class="hljs css">&lt;<span class="hljs-selector-tag">style</span>&gt;
    <span class="hljs-selector-class">.wrapper</span>&#123;
        <span class="hljs-attribute">display</span>: grid;
        <span class="hljs-attribute">padding</span>: <span class="hljs-number">1rem</span>;
        <span class="hljs-attribute">grid-template-columns</span>: <span class="hljs-built_in">repeat</span>(<span class="hljs-number">3</span>,<span class="hljs-number">1</span>fr);
        <span class="hljs-attribute">grid-gap</span>: <span class="hljs-number">1rem</span>;
        <span class="hljs-attribute">grid-auto-rows</span>:<span class="hljs-built_in">minmax</span>(<span class="hljs-number">100px</span>,auto);
        &#125;
    <span class="hljs-selector-class">.wrapper</span>&gt;<span class="hljs-selector-tag">div</span>&#123;
        <span class="hljs-attribute">background</span>: <span class="hljs-number">#ccc</span>;
        <span class="hljs-attribute">padding</span>: <span class="hljs-number">1rem</span>;
    		&#125;
    <span class="hljs-selector-class">.wrapper</span>&gt;<span class="hljs-selector-tag">div</span><span class="hljs-selector-pseudo">:nth-child(odd)</span>&#123;
        <span class="hljs-attribute">background</span>: <span class="hljs-number">#ddd</span>;
    		&#125;
    <span class="hljs-selector-class">.box1</span>&#123;
        <span class="hljs-attribute">grid-column</span>:<span class="hljs-number">1</span>/<span class="hljs-number">3</span>;
        <span class="hljs-attribute">grid-row</span>:<span class="hljs-number">1</span>/<span class="hljs-number">3</span>;
        &#125;
    <span class="hljs-selector-class">.box2</span>&#123;
        <span class="hljs-attribute">grid-column</span>: <span class="hljs-number">3</span>;
        <span class="hljs-attribute">grid-row</span>:<span class="hljs-number">1</span>/<span class="hljs-number">3</span>;
    &#125;
    <span class="hljs-selector-class">.box4</span>&#123;
        <span class="hljs-attribute">grid-column</span>: <span class="hljs-number">2</span>/<span class="hljs-number">4</span>;
    &#125;
    <span class="hljs-selector-class">.box5</span>&#123;
        <span class="hljs-attribute">grid-column</span>: <span class="hljs-number">1</span>/<span class="hljs-number">4</span>;
    &#125;
 &lt;/style&gt;</code></pre>



<p>​        好了，我们来看看效果吧！！！</p>
<p><img src="/articleImg/grid5.jpg" srcset="/img/loading.gif" alt="grid5"></p>
<p>我们发现所有的盒子都发生了变化:我们来分析下</p>
<p>我们对五个盒子进行了操作，但是实际上只用到了两个属性 —–&gt;</p>
<blockquote>
<p><code>grid-column: 1/3;</code> 这个属性代表合并单元格的横轴，后面的1/3(box1)代表合并了从一条线到第三条线的范围(这里的线就是网格线了，这个很好理解，图一中红色黑色的都是网格线，网格线会比盒子多1，例如横向红色线五条是四个盒子，纵向四条线三个盒子)，那么这里横向的1-3就很好理解了，就是当前行第一第二个盒子合并，在下面可以轻松看出，我们没有对box3做任何操作，把box3当做一个盒子，显然box1有两个box3那么宽。</p>
<p><code>grid-row:1/3;</code> 那么很显然这个就是纵向合并了同理以box1为例，box3对比，box1是2倍的box3高度，它在纵向依然合并了两个盒子，第一条线到第三条，想要对谁操作，这个属性加给谁就ok，后面我会把所以属性写出来，以便大家更方便查看，</p>
</blockquote>
<p>看起来文字很多实际上代码不多，接下来我们进行实战看看吧&gt;&gt;&gt;</p>
<h5 id="demo-lt-实战—-gt-模板加媒体查询轻松实现移动pc端-gt"><a href="#demo-lt-实战—-gt-模板加媒体查询轻松实现移动pc端-gt" class="headerlink" title="demo&lt;实战—&gt;模板加媒体查询轻松实现移动pc端&gt;"></a>demo&lt;实战—&gt;模板加媒体查询轻松实现移动pc端&gt;</h5><p>这里我准备了一个demo先来看看吧</p>
<pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"wrapper"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"header"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>九儿的小书屋<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"content"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>hello word<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"silebar"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>联系我们<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>九儿的小书屋<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>shangHai<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>xiaojiu@163.com<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>927898639<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box1"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>titleOne<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box2"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>titleTwo<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box3"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>titleThree<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"footer"</span>&gt;</span>
            Copyright @ 2020
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></code></pre>



<p>看看效果吧（删除掉了各个dom的内容量方便直观观看）</p>
<p><img src="/articleImg/grid6.jpg" srcset="/img/loading.gif" alt="grid6"></p>
<p>可以看到，一个没有css的文件就是这样，下面我们采用模板的方式对他就行布局，我们先来设置一个模板看看吧</p>
<pre><code class="hljs css">&lt;<span class="hljs-selector-tag">style</span>&gt;
        <span class="hljs-selector-tag">body</span>&#123;
            <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
            <span class="hljs-attribute">padding</span>: <span class="hljs-number">1rem</span>;
        &#125;
        <span class="hljs-selector-class">.wrapper</span>&#123;
            <span class="hljs-attribute">display</span>: grid;
            <span class="hljs-attribute">grid-template-areas</span>: 
                <span class="hljs-string">'header header header'</span>
                <span class="hljs-string">'content content silebar'</span>
                <span class="hljs-string">'box1 box2 box3'</span>
                <span class="hljs-string">'footer footer footer'</span>;
            <span class="hljs-attribute">grid-gap</span>: <span class="hljs-number">1rem</span>;
        &#125;
        <span class="hljs-selector-class">.header</span>&#123;
            <span class="hljs-attribute">grid-area</span>: header;
        &#125;
        <span class="hljs-selector-class">.content</span>&#123;
            <span class="hljs-attribute">grid-area</span>: content;
        &#125;
        <span class="hljs-selector-class">.silebar</span>&#123;
            <span class="hljs-attribute">grid-area</span>: silebar;
        &#125;
        <span class="hljs-selector-class">.box1</span>&#123;
            <span class="hljs-attribute">grid-area</span>: box1;
        &#125;
        <span class="hljs-selector-class">.box2</span>&#123;
            <span class="hljs-attribute">grid-area</span>: box2;
        &#125;
        <span class="hljs-selector-class">.box3</span>&#123;
            <span class="hljs-attribute">grid-area</span>: box3;
        &#125;
        <span class="hljs-selector-class">.footer</span>&#123;
            <span class="hljs-attribute">grid-area</span>: footer;
            <span class="hljs-attribute">text-align</span>: center;
        &#125;
        <span class="hljs-selector-class">.header</span>,
        <span class="hljs-selector-class">.content</span>,
        <span class="hljs-selector-class">.silebar</span>,
        <span class="hljs-selector-class">.box1</span>,
        <span class="hljs-selector-class">.box2</span>,
        <span class="hljs-selector-class">.box3</span>,
        <span class="hljs-selector-class">.footer</span>&#123;
            <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid <span class="hljs-number">#ccc</span>;
            <span class="hljs-attribute">padding</span>: .<span class="hljs-number">5rem</span>;
        &#125;
    &lt;/style&gt;</code></pre>



<p>来看看效果吧</p>
<p><img src="/articleImg/grid7.jpg" srcset="/img/loading.gif" alt="grid7"></p>
<p>来分析下吧，看起来很多代码对不，实际上我们只需要关注这个模板即可</p>
<pre><code class="hljs css"><span class="hljs-selector-class">.wrapper</span>&#123;
        <span class="hljs-attribute">display</span>: grid;
        <span class="hljs-attribute">grid-template-areas</span>: 
            <span class="hljs-string">'header header header'</span>
            <span class="hljs-string">'content content silebar'</span>
            <span class="hljs-string">'box1 box2 box3'</span>
            <span class="hljs-string">'footer footer footer'</span>;
        <span class="hljs-attribute">grid-gap</span>: <span class="hljs-number">1rem</span>;
    &#125;</code></pre>

<p>可以看到一共有四行，第一行三个都是header表示第一行header独占一行占了所有位置，那么为什么是三个header呢，这个其实是不固定的，因为我们在第三行放了三个格子三个div即box123，所以我们应当在设计模板的时候考虑一行最多的那一行会放多少个div即多少个格子，我们的这个模板给他加上一个border就可以发现它就是一行三个格子一共四行十二个格子，当然这个随意你修改都可以，在下面给各个class单独设置属性的时候只需要使用grid-area: xxx;进行关联就好，上面模板用的这些词汇不固定，即使使用abc都可以，当然我们需要语义化以便更直观看出来，这里你可以多做尝试，其实就是一个拼图游戏，自己随意尝试，然后在下面关联上模板即可，我们来看看这个模板占比：</p>
<table>
<thead>
<tr>
<th align="center">header</th>
<th align="center">header</th>
<th align="center">header</th>
</tr>
</thead>
<tbody><tr>
<td align="center">content</td>
<td align="center">content</td>
<td align="center">silebar</td>
</tr>
<tr>
<td align="center">box1</td>
<td align="center">box2</td>
<td align="center">Box3</td>
</tr>
<tr>
<td align="center">footer</td>
<td align="center">footer</td>
<td align="center">footer</td>
</tr>
</tbody></table>
<p>这是pc端的模块，假设我们在移动端呢，我们的手机和电脑屏幕相差甚远如何做到呢，在以前我们对pc移动的自适应可能需要写到两套css代码而用Grid的模板我们可以轻松解决，我们只需要修改他的模板即可，下面是代码：</p>
<pre><code class="hljs css">@media(max-width: 500px)&#123;
            <span class="hljs-selector-class">.wrapper</span>&#123;
                <span class="hljs-attribute">grid-template-areas</span>: 
                    <span class="hljs-string">'header'</span>
                    <span class="hljs-string">'content'</span>
                    <span class="hljs-string">'silebar'</span>
                    <span class="hljs-string">'box1'</span>
                    <span class="hljs-string">'box2'</span>
                    <span class="hljs-string">'box3'</span>
                    <span class="hljs-string">'footer'</span>;
            &#125;
        &#125;</code></pre>



<p>只需要简单的一个媒体查询：当宽度小于500px(据实际情况而定)的时候，我们把模板改为各个div都是独占一行的，pc端就是上图，让我们看看移动端</p>
<p><img src="/articleImg/grid8.jpg" srcset="/img/loading.gif" alt="grid8"></p>
<p>通过一个模板轻松改变移动pc的适应，是不是很神奇呢。</p>
<h5 id="Flex和Grid的不同之处"><a href="#Flex和Grid的不同之处" class="headerlink" title="Flex和Grid的不同之处"></a>Flex和Grid的不同之处</h5><p>我们常常把Flex布局称之为一维布局(一次只能处理一个维度（一行或者一列）上的元素布局)，so，Grid便是所谓的二维布局了(可以同时处理行和列上的布局。)</p>
<p><strong>网格容器 VS Flex容器</strong></p>
<p><strong>网格属性 VS Flex属性</strong></p>
<blockquote>
<p>Flex:</p>
<p>flex是flexible box（弹性布局）的简介，是一个一维系统，用来为盒状模型提供最大的灵活性。</p>
<p><strong>使用：</strong>任何容器（行内元素可设置为display:inline-block）;</p>
<p><strong>特点：</strong>空间分布在行中进行，而非整体</p>
<p>Grid</p>
<p>Gird Layout(css网格布局)是css中最强大的布局系统，是一个二维系统，可以同时处理行和列，可以通过将css规则用于父元素（网格容器）和该元素的子元素（网格元素）来使用网格布局。</p>
<p> 使用：对父元素设置dispay：grid;grid-template-colums和grid-template-rows来设置几行几列，然后对子元素设置占据几行几列</p>
<p>特点：二维网格结构，十分便于操作</p>
</blockquote>
<p>这两者的核心是：一个盒子里有很多小盒子，如何排列？</p>
<p>flex就是沿着一条线铺下去，这个线可能水平，也可能垂直，这个平铺的方向用flex-direction来控制。</p>
<p>所以flex才有换行命令。而且当同级小盒子很多的时候，往往动一发而动全身，很不方便。</p>
<p>grid是把盒子用线分成很多份，把小盒子一个个填进去。</p>
<p><strong>所以我们在使用grid布局的时候考虑的往往是如何 排列我们的盒子呢，或者说，这个拼图游戏怎么拼才好呢？</strong></p>
<h5 id="Grid的常用属性集合"><a href="#Grid的常用属性集合" class="headerlink" title="Grid的常用属性集合"></a>Grid的常用属性集合</h5><table>
<thead>
<tr>
<th>常用属性</th>
<th>介绍</th>
</tr>
</thead>
<tbody><tr>
<td>display: grid;</td>
<td>表示为网格布局，和flex布局中的display：flex意义相同</td>
</tr>
<tr>
<td>grid-template-columns</td>
<td>创建网格的列数，除了百分比的形式之外，还支持各种单位的组合形式</td>
</tr>
<tr>
<td>grid-template-rows</td>
<td>属性值和grid-template-columns的属性值完全一样。</td>
</tr>
<tr>
<td>grid-gap</td>
<td>可以取一或两个值，表示行列之间的间隙。</td>
</tr>
<tr>
<td>grid-template-areas</td>
<td>通过引用 grid-area 属性指定的 网格区域(Grid Area) 名称来定义网格模板。</td>
</tr>
<tr>
<td>grid-auto-flow: dense|row(default)|column</td>
<td>告诉自动布局算法依次填充每行，根据需要添加新行/列</td>
</tr>
<tr>
<td>justify-items: start|end|center|stretch(default)</td>
<td>沿着 行轴线(row axis) 对齐 网格项(grid items) 内的内容</td>
</tr>
<tr>
<td>align-items:start|end|start|center|stretch</td>
<td>沿着 列轴线(row axis) 对齐 网格项(grid items) 内的内容</td>
</tr>
<tr>
<td>grid-auto-columns:</td>
<td>隐式网格的宽度</td>
</tr>
</tbody></table>
<h5 id="兼容性"><a href="#兼容性" class="headerlink" title="兼容性"></a>兼容性</h5><p>作为前端，我们逃不掉的一个问题就是兼容性问题了，看似强大的grid布局为什么在日常中使用的却不多呢，那就是因为目前的grid布局还不够普及导致兼容性还较差，在低版本的浏览器是无法使用的，但是前段技术进步很快，更新很快，相信在移动端目前grid布局已经支持性很高了，在目前互联网飞速发展的时代，我认为，作为目前最强大的css布局方案，grid终究会是前端布局的一个主流方向，初次使用，感到新鲜神奇，也许目前的兼容性还没有flex好，但是慢慢的应该grid布局就会兼容更多了，大家可以先学习了，多做尝试，你是否也会觉得他很神奇呢？</p>
<h4 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h4><p>​        作者 ： 小九</p>
<p>​        时间 ： 2020/03/31</p>
<p>​        如有错漏之处，请纠正，看官们点个赞吧。</p>
<hr>
<center>欲望以提升热忱，毅力以磨平高山。</center>


            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/css/">css</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E5%B8%83%E5%B1%80/">布局</a>
                    
                      <a class="hover-with-bg" href="/tags/grid/">grid</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/posts/840b49ba.html">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">event loop事件循环机制</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/posts/160dac1d.html">
                        <span class="hidden-mobile">三栏布局的实现方法</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script type="text/javascript">
    function loadValine() {
      addScript('https://cdn.staticfile.org/valine/1.4.14/Valine.min.js', function () {
        new Valine({
          el: "#vcomments",
          app_id: "3PpvuTN5QkO4Tih7TqE1W5u8-gzGzoHsz",
          app_key: "2URikzfu2z1jtCXMp3Sy6Oin",
          placeholder: "说点什么",
          path: window.location.pathname,
          avatar: "retro",
          meta: ["nick","mail","link"],
          pageSize: "10",
          lang: "zh-CN",
          highlight: false,
          recordIP: false,
          serverURLs: "",
        });
      });
    }
    createObserver(loadValine, 'vcomments');
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://valine.js.org" target="_blank" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->



<!-- <script>
//去掉畅言下面的跳转连接
  //  声明定时器
var timer = null
//  检查dom是否执行完成
function checkDom() {
    let dom = document.querySelector('.service-wrap-w')
    if(dom) {
      console.log(dom)
         //  执行dom加载完成后的操作
         dom.innerHTML = ''
        //  清除定时器
        if(!timer) {
            clearTimeout(timer)
        }
    } else {
        //  自我调用
        timer = setTimeout(checkDom, 0)
    }
}
//  首次执行
checkDom()
</script> -->
      
    </main>

    
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
    

    
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    

    

    <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <!-- <a  rel="nofollow noopener"><span class="motto">故事若不曲折怎么教人成长</span></a> -->

      <!-- <a rel="nofollow noopener"><span class="motto">xiaojiu</span></a> -->
      <!-- <i class="iconfont icon-love"></i> -->
      <a rel="nofollow noopener">

        <!-- <span class="motto"> 可惜故事太长只有风听我讲</span></a> -->
        
        <span class="motto"> 黄粱一梦、山水万重、人间总相逢</span></a>
        <!-- <span class="motto"> blog</span></a> -->

    </div>
    


    

    
    <div class="xiaojiu">
      <span id="xiaojiu_container_site_pv" style="display: none;">本站已经被访问- <span id="xiaojiu_value_site_pv"
          style="margin: 0 3px;"> </span> -次啦</span>
      <span id="xiaojiu_container_site_uv" style="display: none;">已经有- <span id="xiaojiu_value_site_uv"
          style="margin: 0 3px;"> </span> -个小伙伴来过啦</span>
    </div>


    <div class="date">
      <span id="timeDate">载入天数...</span>
      <span class="times" id="times">载入时分秒...
      </span>
      <img class="time" src="/img/sml.gif" srcset="/img/loading.gif" alt="">
      <script>
        var now = new Date();
        function createtime() {
          var grt = new Date("05/08/2018 00:00:00");//此处修改你的建站时间或者网站上线时间
          now.setTime(now.getTime() + 250);
          days = (now - grt) / 1000 / 60 / 60 / 24;
          dnum = Math.floor(days);
          hours = (now - grt) / 1000 / 60 / 60 - (24 * dnum);
          hnum = Math.floor(hours);
          if (String(hnum).length == 1) {
            hnum = "0" + hnum;
          }
          minutes = (now - grt) / 1000 / 60 - (24 * 60 * dnum) - (60 * hnum);
          mnum = Math.floor(minutes);
          if (String(mnum).length == 1) {
            mnum = "0" + mnum;
          }
          seconds = (now - grt) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
          snum = Math.round(seconds);
          if (String(snum).length == 1) {
            snum = "0" + snum;
          }
          document.getElementById("timeDate").innerHTML = "本站已运行&nbsp" + dnum + "&nbsp天";
          document.getElementById("times").innerHTML = hnum + "&nbsp小时&nbsp" + mnum + "&nbsp分&nbsp" + snum + "&nbsp秒";
        }
        setInterval("createtime()", 250);
      </script>
    </div>
</footer>
<!-- <script src="https://api.lzwzw.cn/public/js/xiaojiu.js"></script> -->
<!-- <script src="/js/xiaojiu.js"></script> -->
<script src="/js/message.js"></script>

<style>
  .xiaojiu {
    margin-top: 14px !important;
    background-image: linear-gradient(135deg, deeppink, dodgerblue);
    font-weight: bold;
    -webkit-background-clip: text;
    -moz-background-clip: text;
    background-clip: text;
    box-decoration-break: clone;
    -webkit-box-decoration-break: clone;
    -moz-box-decoration-break: clone;
    color: transparent;
    position: relative;
  }

  .date {
    background-image: linear-gradient(135deg, deeppink, dodgerblue);
    font-weight: bold;
    -webkit-background-clip: text;
    -moz-background-clip: text;
    background-clip: text;
    box-decoration-break: clone;
    -webkit-box-decoration-break: clone;
    -moz-box-decoration-break: clone;
    color: transparent;
    position: relative;
  }
</style>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>







  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 6,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "神奇的grid布局&nbsp;",
      ],
      cursorChar: "✨",
      typeSpeed: 80,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
      icon: "❡"
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  



  <script>(function (i, s, o, g, r, a, m) {
      i['DaoVoiceObject'] = r;
      i[r] = i[r] ||
        function () {
          (i[r].q = i[r].q || []).push(arguments);
        };
      i[r].l = 1 * new Date();
      a = s.createElement(o);
      m = s.getElementsByTagName(o)[0];
      a.async = 1;
      a.src = g;
      a.charset = 'utf-8';
      m.parentNode.insertBefore(a, m);
    })(window, document, 'script', ('https:' === document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/2b2e276c.js", 'daovoice');
    daovoice('init', {
      app_id: "2b2e276c",
    });
    daovoice('update');
  </script>










  </div>
  
</body>

</html>
<script>

  // https://uploadbeta.com/api/pictures/random/?key=BingEverydayWallpaperPicture
  // https://source.unsplash.com/random  速度慢  有图还不错
  //https://uploadbeta.com/api/pictures/random/?key=%E6%8E%A8%E5%A5%B3%E9%83%8E 随机女图
  // https://api.jlongyan.cn/api/paper/random
  function checkWallaper() {
    fetch('https://source.unsplash.com/random', {
      method: 'GET',
      mode: 'cors',
    })
      .then(res => {
        setWallaper(res.url)
        localStorage.setItem('blogWallaper',res.url)
        return res.json()
      })
      // .then(res => {
      //   console.log(res);
      //   console.log("%c随机背景图片接口开放%c，随机壁纸api详情见博客,%c小九---!", "color:red", "", "color:orange;font-weight:bold")
      //   setWallaper(res.data.CoverImg)
      //   localStorage.setItem('blogWallaper',res.data.CoverImg)
      // })
      .catch(console.error)
  }

  if(localStorage.getItem('blogWallaper')){
    setWallaper(localStorage.getItem('blogWallaper'))
  }else{
    checkWallaper()
  }

  //设置壁纸
  function setWallaper(url){
    document.getElementById('indexBackground').style.backgroundImage = "url(" + url + ")";
  }

  let timer = null
  //  检查dom是否存在当前页面  监听 
  function watchYiyan() {
    let dom = document.getElementById('yiyan')
    if (dom) {
      fetch('https://v1.hitokoto.cn')
        .then(response => response.json())
        .then(data => {
          dom.innerText = data.hitokoto
        })
        .catch(console.error)
      if (!timer) {
        clearTimeout(timer)
      }
    } else {
      timer = setTimeout(watchYiyan, 0)
    }
  }
  //  首次执行
  watchYiyan()

  setTimeout(() => {
    clearTimeout(timer)
  }, 200);


</script>
